<script setup lang="ts">
import HomeContent from '@/components/HomeContent/index.vue'
import { useUserStore } from '@/stores'
import { Plus, Upload } from '@element-plus/icons-vue'
import { UploadFile } from 'element-plus'
import { putAvatarAPI } from '@/services/user/user'
import { ref, watch } from 'vue'
const userStore = useUserStore()
const imgUrl = ref(userStore.userInfo?.userInfo?.avatar)
const uploadRef = ref()

const onSelectFile = (uploadFile: UploadFile) => {
  // 基于 FilerReader 的图片预览功能
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw!)
  reader.onload = () => {
    imgUrl.value = reader.result as string
  }
}

// 上传头像
const onUpdateAvatar = async () => {
  if (!imgUrl.value) {
    ElMessage({
      type: 'error',
      message: '请选择图片'
    })
  }
  await putAvatarAPI({
    id: userStore.userInfo.userInfo.id,
    url: imgUrl.value
  })
  ElMessage({
    type: 'success',
    message: '修改成功'
  })
}

watch(
  () => userStore.userInfo,
  _newVal => {
    imgUrl.value = userStore.userInfo.userInfo.avatar
  }
)
</script>
<template>
  <HomeContent>
    <template #title>更换头像</template>
    <template #content>
      <el-upload
        ref="uploadRef"
        class="avatar-uploader"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="onSelectFile"
      >
        <img v-if="imgUrl" :src="imgUrl" class="avatar" />
        <img v-else src="../../../assets/avatar.jpg" width="300" />
      </el-upload>
      <div class="btn">
        <el-button
          @click="uploadRef.$el.querySelector('input').click()"
          type="primary"
          :icon="Plus"
          size="large"
        >
          选择图片
        </el-button>
        <el-button
          @click="onUpdateAvatar"
          type="success"
          :icon="Upload"
          size="large"
        >
          上传头像
        </el-button>
      </div>
    </template>
  </HomeContent>
</template>

<style scoped lang="less">
.avatar-uploader {
  width: 300px;
  height: 300px;
}
:deep(.el-upload) {
  width: 100%;
  height: 100%;
}
.avatar {
  width: 100%;
  height: 100%;
}
.btn {
  margin-top: 30px;
  width: 300px;
  display: flex;
  justify-content: space-evenly;
}
</style>
